package com.yykj.prescription.server.service.impl;

import com.yykj.common.service.RedisService;
import com.yykj.prescription.server.model.entity.prescription.Prescription;
import com.yykj.prescription.server.model.entity.prescription.PrescriptionTask;
import com.yykj.prescription.server.model.repository.prescription.PrescriptionRepository;
import com.yykj.prescription.server.model.repository.prescription.PrescriptionTaskRepository;
import com.yykj.prescription.server.service.PrescriptionTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j

public class PrescriptionTaskServiceImpl implements PrescriptionTaskService {
    @Override
    public void expirePrescriptionTask() {
        String key = "task_expire_key";
        long value = System.currentTimeMillis() + 2000;
        if(redisService.lock(key, String.valueOf(value))){
            log.info("开始检查有无过期的处方。。。");
            List<PrescriptionTask> list = prescriptionTaskRepository.findAllByExpireTimeLessThanEqual(LocalDateTime.now());
            if (list != null && list.size() > 0) {
                log.info("有过期任务，开始执行。。。");
                List<String> ids = list.stream().map(PrescriptionTask::getPrescriptionId).collect(Collectors.toList());
                List<Prescription> prescriptionList = prescriptionRepository.findAllByPrescriptionIdIn(ids);
                for (Prescription prescription : prescriptionList) {
                    prescription.setExpireTime(LocalDateTime.now());
                    prescription.setStatus(3);
                }
                //更新处方状态
                prescriptionRepository.saveAll(prescriptionList);
                //任务列表里删除
                prescriptionTaskRepository.deleteAll(list);
                log.info("执行完成。。。");
            } else {
                log.info("没有过期任务。。。");
            }
            redisService.unlock(key,String.valueOf(value));
        }

    }

    private PrescriptionTaskRepository prescriptionTaskRepository;

    private PrescriptionRepository prescriptionRepository;

    private RedisService redisService;

    @Autowired
    public void setPrescriptionTaskRepository(PrescriptionTaskRepository prescriptionTaskRepository) {
        this.prescriptionTaskRepository = prescriptionTaskRepository;
    }

    @Autowired
    public void setPrescriptionRepository(PrescriptionRepository prescriptionRepository) {
        this.prescriptionRepository = prescriptionRepository;
    }

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }
}
